package com.controller;

import com.Dto.UserDto;
import com.common.Result;
import com.pojo.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.UUID;

@CrossOrigin
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;



    /**
     * 过期时间30min
     */
    private static final long SESSION_EXPIRE_TIME = 30;//min

    /**
     * 登录功能,后端生成令牌，令牌存在redis数据库，用户登录不可能永远生效，存30分钟，30分钟令牌没了
     * 登录成功把令牌给前端，功能携带令牌请求，后端校验令牌是否存在（到redis)。
     */
    @PostMapping("/login")
    public Result<UserDto> login(@RequestBody User user) {
        Result result = new Result<>();
        System.out.print(user.getUserName());
        System.out.print(user.getPassword());
        String userName = user.getUserName();
        String password = user.getPassword();
        User user1 = userService.getUserByLogin(userName, password);
        try {
            if (user1 != null) {//登录成功
                System.out.println("Login successful");
                System.out.print("token"+user1.getId()+"\n");
                //生成Token令牌
                String token = UUID.randomUUID()+""; //UUID根据电脑的各种状态生成的，唯一。
                System.out.print(token+"\n");
                //存在Redis数据库
                redisTemplate.opsForValue().set(token,user1,Duration.ofMinutes(30L));
                Object storedValue = redisTemplate.opsForValue().get(token);
                if (storedValue != null) {
                    System.out.println("Token value in Redis: " + storedValue.toString());
                } else {
                    System.out.println("Token not found in Redis");
                }

                System.out.println("Token stored in Redis");
                UserDto userDto = new UserDto();
                userDto.setToken(token);
                userDto.setId(user1.getId());
                userDto.setType(user1.getRoleId());

                System.out.print(userDto.getId());
                System.out.print(userDto.getToken());
                System.out.print(userDto.getType());

                result.setSuc(userDto);
            } else {
                result.setFail("登录失败");
            }
        } catch (Exception e) {
            System.out.println("Error occurred while setting value in Redis: " + e.getMessage());
            result.setFail("登录失败");
        }
        return result;
    }
}
/*
        Result result = new Result<>();
        try{
            String path = userService.Login(user);
            if(path != null){
                result.setSuc(path);
            }else{
                result.setFail("登录失败");
            }
        }catch (Exception e){
            result.setFail("登录失败");
        }
        return result;
}

/*
    @Autowired
    private UserService userService;
    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
        User user = userService.findByUsername(username);
        if (user == null) {
            return "用户不存在";
        }

        // 进行密码验证
        if (!user.getPassword().equals(password)) {
            return "密码错误";
        }

        // 登录成功，获取用户角色
        List<Role> roles = userService.getUserRoles(user.getId());
        String role = roles.get(0).getRoleName(); // 假设一个用户只有一个角色


        // 根据角色进行跳转
        if (role.equals("机构管理员")) {
            return "redirect:/admin"; // 跳转到机构管理员后台
        } else if (role.equals("咨询师")) {
            return "redirect:/counselor"; // 跳转到咨询师后台
        } else if (role.equals("督导")) {
            return "redirect:/supervisor"; // 跳转到督导后台
        }

        return "未知角色";
    }*/
